package com.auto.autoapp.task

import android.view.accessibility.AccessibilityNodeInfo
import com.auto.autoapp.constants.Dy
import com.auto.autoapp.constants.SearchPageId
import com.auto.autoapp.constants.VideoPageId
import com.auto.autoapp.model.CommentPrivateMessageSetting
import com.auto.autoapp.model.Direction
import com.auto.autoapp.step.backToSearchPage
import com.auto.autoapp.step.changeSearchResultTab
import com.auto.autoapp.step.checkLogin
import com.auto.autoapp.step.clickCommentBtn
import com.auto.autoapp.step.clickLike
import com.auto.autoapp.step.exchangeVideo
import com.auto.autoapp.step.focusUser
import com.auto.autoapp.step.replyComment
import com.auto.autoapp.step.scroll
import com.auto.autoapp.step.sendPrivateMsg
import com.auto.autoapp.step.toDyIndex
import com.auto.autoapp.util.SpUtil
import com.auto.autoapp.util.StringUtil
import com.auto.autoapp.util.Util
import com.auto.autoapp.util.addLog
import com.auto.autoapp.util.clickOrTap
import com.auto.autoapp.util.getNodeById
import com.auto.autoapp.util.getNodeList
import com.ven.assists.AssistsCore
import com.ven.assists.AssistsCore.des
import com.ven.assists.AssistsCore.findById
import com.ven.assists.AssistsCore.setNodeText
import com.ven.assists.service.AssistsService
import com.ven.assists.stepper.Step
import com.ven.assists.stepper.StepCollector
import com.ven.assists.stepper.StepImpl
import kotlinx.coroutines.delay
import kotlin.random.Random

/**
 * 搜索视频评论区意向客户私信
 * 搜索关键字查找到相关视频，对视频评论区意向客户进行私信
 */
class CommentPrivateMsgTask : StepImpl() {
    private var setting = CommentPrivateMessageSetting()
    private var maxCommentCount = 20
    private var commentList = mutableListOf<String>()
    private var currentAvatarNode: AccessibilityNodeInfo? = null
    override fun onImpl(collector: StepCollector) {
        setting = SpUtil.getCommentPrivateMsgSetting()
        maxCommentCount = setting.maxCommentCount
        collector.next(1) {
            commentList.clear()
            return@next toDyIndex()
        }
            // Step 2: 获取抖音号，检查登录状态
            .next(2) {
                val loginResult = checkLogin()
                if (loginResult.isSuccess) {
                    return@next Step.get(3)
                }
                return@next Step.none
            }
            //点击首页搜索，跳转搜索页面
            .next(3) {
                val searchNodeResult = Dy.ID_INDEX_SEARCH_NODE.clickOrTap()
                if (searchNodeResult.isFailure) {
                    addLog("未找到搜索入口，请重试")
                    AssistsCore.back()
                    delay(1000)
                    return@next Step.repeat
                }
                return@next Step.get(4)
            }
            //进入搜索页面
            .next(4) {
                val editText = AssistsCore.findById(Dy.ID_SEARCH_INPUT).firstOrNull()
                if (editText != null) {
                    editText.setNodeText(setting.searchKeywords)
                    delay(1000)
                    Dy.SEARCH_BTN.clickOrTap()
                    addLog("已执行搜索")
                    delay(2000)
                    val changeTabResult = changeSearchResultTab("视频")
                    if (changeTabResult.isSuccess) {
                        delay(3000)
                        val videoListResult = SearchPageId.TAB_CONTENT_RV.getNodeById()
                        if (videoListResult.isFailure) {
                            addLog("未找到视频列表")
                            return@next Step.none
                        }
                        delay(1000)
                        val videoList = videoListResult.getOrNull()!!
                        val childCount = videoList.childCount
                        addLog("视频列表数量：$childCount")
                        val clickResult = videoList.getChild(0).clickOrTap()
                        if (clickResult.isSuccess) {
                            addLog("点击视频，开始浏览")
                            return@next Step.get(5)
                        } else {
                            addLog("点击视频失败")
                            return@next Step.none
                        }
                    }
                    return@next Step.none

                } else {
                    addLog("搜索输入框未找到")
                    return@next Step.none
                }
            }
            .next(5) {
                val seconds = setting.videoSeconds.coerceAtLeast(1)
                addLog("开始浏览视频：${seconds}s")
                delay(seconds * 1000L)

                //是否已经点过赞
                val hasLiked =
                    Dy.ID_VIDEO_LIKE.getNodeList().getOrNull()?.firstOrNull()?.des()
                        ?.contains("已") == true
                if (hasLiked) {
                    addLog("已经点过赞，跳过点赞逻辑")
                } else {
                    val likeProb = setting.likeProbability.coerceIn(0, 100)
                    val roll = Random.nextInt(0, 100)
                    val needLike = roll < likeProb
                    addLog("点赞概率：${likeProb}%,当前点数：$roll,是否执行点赞：${if (needLike) "执行" else "不执行"}")
                    if (needLike) {
                        val likeResult = clickLike()
                        if (likeResult.isSuccess) {
                            delay(2000)
                        } else {
                            addLog("点赞失败")
                        }
                    } else {
                        addLog("点赞跳过")
                    }
                }
                return@next Step.get(6)
            }.next(6) {
                delay(2000)
                val commentBtnResult = clickCommentBtn()
                if (commentBtnResult.isFailure) {
                    addLog("无法打开评论区，返回抖音首页重新开始")
                    AssistsCore.back()
                    delay(1000)
                    return@next Step.get(1)
                }
                delay(1500)
                addLog("已进入评论区，开始检查评论")
                return@next Step.get(7)

            }.next(7) {
                while (commentList.size < maxCommentCount) {
                    addLog("已检查评论数量：${commentList.size},最多检查：${maxCommentCount}")
                    val commentListResult = VideoPageId.ID_COMMENT_RV.getNodeById()

                    val commentListNode = commentListResult.getOrNull()!!
                    val childCount = commentListNode.childCount
                    if (childCount == 0) {
                        addLog("评论数量为0，开始返回")
                        AssistsCore.back()
                        return@next Step.get(8)
                    }

                    var hasNewComment = false
                    for (i in 0 until childCount) {
                        val cItem = commentListNode.getChild(i)
                        val contentNode = cItem.findById(Dy.ID_COMMENT_CONTENT).firstOrNull()
                        var contentNodeVisible = contentNode?.isVisibleToUser == true
                        val content = contentNode?.text?.toString() ?: ""
                        if (contentNodeVisible) {
                            if (commentList.contains(content)) {
                                continue
                            }
                            val keyMatch = Util.matchKeyword(
                                content,
                                setting.commentIncludeKeywords,
                                setting.commentExcludeKeywords
                            )
                            hasNewComment = true
                            if (!keyMatch) {
                                continue
                            }
                            commentList.add(content)
                            currentAvatarNode =
                                cItem.findById(VideoPageId.COMMENT_AVATAR).firstOrNull()
                            return@next Step.get(9)
                        } else {
                            continue
                        }
                    }

                    //评论数量没有变化，视为评论全部加在完毕
                    if (!hasNewComment) {
                        addLog("已检索玩全部评论")
                        AssistsCore.back()
                        return@next Step.get(8)
                    }
                    delay(2000)
                    scroll(VideoPageId.ID_COMMENT_RV, Direction.B2T, to = 0.1f)
                    delay(1200)

                }
                return@next Step.get(8)
            }
            .next(8) {
                commentList.clear()
                val exchange = exchangeVideo()
                if (exchange.isFailure) {
                    addLog("滑屏进入下一个视频失败")
                    return@next Step.none
                }
                return@next Step.get(5)
            }.next(9) {
                if (currentAvatarNode == null) {
                    return@next Step.get(8)
                }

                val clickAvatar = currentAvatarNode!!.clickOrTap()
                if (clickAvatar.isSuccess) {
                    return@next Step.get(10)
                }
                AssistsCore.back()

                return@next Step.get(8)
            }.next(10) {
                addLog("进入个人主页")
                delay(2000)

                val focusProp = setting.followProbability.coerceIn(0, 100)
                val roll = Random.nextInt(0, 100)
                val needFocus = roll < focusProp
                addLog("关注：${focusProp}%,当前点数：$roll,是否执行关注：${if (needFocus) "执行" else "不执行"}")
                if (needFocus) {
                    focusUser()
                    delay(2000)
                }
                val replyResult = setting.dmProbability.coerceIn(0, 100)
                val needPm = roll < replyResult
                if (needPm) {
                    val pmMsg = setting.dmMessages.random()
                    val pmResult = sendPrivateMsg(pmMsg)
                    addLog("私信是否发送成功:${pmResult.isSuccess}")
                    delay(2000)
                    AssistsCore.back()
                }
                delay(2000)
                AssistsCore.back()
                //返回之后 需要将评论上拉一下
                delay(2000)
                scroll(VideoPageId.ID_COMMENT_RV, Direction.B2T, to = 0.7f)
                delay(1200)
                return@next Step.get(7)
            }
    }
}